package com.intelligentpension.kotlinsimpleroom

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.intelligentpension.kotlinsimpleroom.dao.RoomBasic
import com.intelligentpension.kotlinsimpleroom.dao.User
import java.util.ArrayList

class MainActivity : AppCompatActivity() {
    private lateinit var editText: EditText
    private lateinit var add: Button
    private lateinit var delete: Button
    private lateinit var recyclerView: RecyclerView
    private lateinit var linearLayout: LinearLayoutManager
    private lateinit var mAdapter: MainAdapter;
    private lateinit var database: RoomBasic;
    private var dataList: MutableList<User> = ArrayList()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        editText = findViewById<EditText>(R.id.edit_text)
        add = findViewById<Button>(R.id.bt_add)

        delete = findViewById<Button>(R.id.bt_reset)
        recyclerView = findViewById<RecyclerView>(R.id.recycler)

        database = RoomBasic.getDatabase(this@MainActivity)

        var dataList1 = database.UserDao().selectAll()
        if (dataList1 != null)
            dataList.addAll(dataList1)

        linearLayout = LinearLayoutManager(this@MainActivity)
        recyclerView.layoutManager = linearLayout
        mAdapter = MainAdapter(this@MainActivity, dataList)
        recyclerView.adapter = mAdapter;

        add.setOnClickListener {
            var message = editText.text.toString().trim()
            if (message.isNotEmpty()) {
                var data: User = User()
                data.phone = message
                database.UserDao().insert(data)

                editText.setText("")
                dataList.clear()
                dataList.addAll(database.UserDao().selectAll()!!)
                mAdapter.notifyDataSetChanged()
            }
        }

        delete.setOnClickListener {
            database.UserDao().reset(dataList)
            dataList.clear()
            var dataList1 = database.UserDao().selectAll()
            if (dataList1 != null)
                dataList.addAll(dataList1)
            mAdapter.notifyDataSetChanged()

        }
    }
}